package com.zhangfb95.crosschain.server.infra.util;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

/**
 * @author zhangfubing
 * @since 2024/2/5
 */
public class GroovyObjectUtil {

    private GroovyObjectUtil() {
    }

    public static Object invokeMethod(String scriptText, String name, Object[] args) {
        try (GroovyClassLoader loader = new GroovyClassLoader()) {
            Class<?> scriptClass = loader.parseClass(scriptText);
            GroovyObject scriptInstance = (GroovyObject) scriptClass.getDeclaredConstructor().newInstance();
            return scriptInstance.invokeMethod(name, args);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
